<?php

namespace app\base\command;


use app\base\model\RedianData;
use app\base\model\RedianTask;
use app\base\service\TaskService;
use app\base\service\WsSendService;
use think\admin\Command;
use think\console\Input;
use think\console\Output;
/**
 * 批量下载视频
 * Class SmsNum
 * @package app\common\command
 */
class BatchDownloadVideo extends Command
{
    /**
     * 配置指令
     */
    protected function configure()
    {
        $this->setName('xbase:BatchDownloadVideo');
        $this->setDescription('BatchDownloadVideo');
    }

    protected function execute(Input $input, Output $output)
    {
        $queue_data = $this->queue->data;
        $task_id = $queue_data['task_id'];
        $task_run_log_id = $queue_data['task_run_log_id'];
        $this->setQueueProgress("任务ID_{$task_id}：开始执行");
        $redian_datas = RedianData::mQuery()->where([
            "task_id"=>$task_id,
            'task_run_log_id'=>$task_run_log_id,
            'video_status'=>3
        ])->select()->toArray();
        $num = count($redian_datas);
        $total = $num+10;
        $count = 0;
        // 创建存储目录
        $videoDir = $this->app->getRootPath() . "public/upload/video/{$task_id}_{$task_run_log_id}";
        if (!is_dir($videoDir)) {
            mkdir($videoDir, 0755, true);
        }
        $save_video_paths = [];
        foreach ($redian_datas as $redian_data) {
            try {
                $this->queue->message($total, ++$count, "正在处理第 {$count}/{$num} 个视频");

                // 净化文件名
                $video_title = preg_replace('/[^\p{L}\p{N}\-_]/u', '', $redian_data['video_title']);
                $video_file_name = $video_title. ".mp4";
                $save_path = $videoDir . DIRECTORY_SEPARATOR . $video_file_name;

                // 下载视频
                $video_url = $redian_data['video_url'];
                $this->downloadVideo($video_url, $save_path);
//                if(strpos($video_url,"dev.blueant.pro")!==false){
//                    str_replace("http://dev.blueant.pro", $this->app->getRootPath() . "public",$video_url);
//                    $savePath = $video_url;
//                }else{
//                    $this->downloadVideo($video_url, $save_path);
//                }

                $this->queue->message($total, $count, "第 {$count} 个视频处理成功");
                RedianData::mQuery()->where([
                    "id"=>$redian_data['id']
                ])->update([
                    "save_video_path"=>$save_path
                ]);
                $save_video_paths[]=$save_path;

            } catch (\Exception $e) {

                $this->queue->message($total, $count, "第 {$count} 个视频处理失败: " . $e->getMessage());
            }
        }
        if(empty($save_video_paths)){
            $this->setQueueError("没有下载到任何视频");
        }
        //将成功生成的视频打包成压缩包并生成下载地址
        $zip_file_name = "{$task_id}_{$task_run_log_id}.zip";
        $zip_file_path = $videoDir . DIRECTORY_SEPARATOR . $zip_file_name;
        $zip = new \ZipArchive();
        if ($zip->open($zip_file_path, \ZipArchive::CREATE) !== true) {
            $this->setQueueError("压缩文件创建失败");
        }
        foreach ($save_video_paths as $save_path) {
            $zip->addFile($save_path, basename($save_path));
        }
        $zip->close();
        $zip_url = "http://dev.blueant.pro/upload/video/{$task_id}_{$task_run_log_id}/{$zip_file_name}";
        if($task_run_log_id){
            $this->app->db->name("task_run_log")->where(["id"=>$task_run_log_id])->update([
                "zip_url"=>$zip_url
            ]);
        }else{
            RedianTask::mQuery()->where(["id"=>$task_id])->update([
                "zip_url"=>$zip_url,
            ]);
        }
        $this->setQueueSuccess("任务完成，成功处理 {$count}/{$total} 个视频");


    }

    /**
     * 下载图片到本地
     */
    private function downloadVideo(string $url, string $savePath): void
    {
        //判断url是否为本地路径即访问域名为dev.blueant.pro,如果是则去本地路径
        // 使用cURL流式下载
        $ch = curl_init($url);
        $fp = fopen($savePath, 'wb');

        curl_setopt_array($ch, [
            CURLOPT_FILE => $fp,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_TIMEOUT => 3000, // 5分钟超时
            CURLOPT_USERAGENT => 'Mozilla/5.0',
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false
        ]);

        if (!curl_exec($ch)) {
            fclose($fp);
            unlink($savePath); // 删除可能的部分文件
            throw new \Exception("视频下载失败: " . curl_error($ch));
        }

        fclose($fp);
        curl_close($ch);

        // 验证文件完整性
        if (!file_exists($savePath) || filesize($savePath) === 0) {
            throw new \Exception("视频保存失败，文件为空");
        }



    }



}
